package com.SmartCare.service.impl.role;

import cn.hutool.core.bean.BeanUtil;
import com.SmartCare.pojo.homeInfo.CareHomeDetails;
import com.SmartCare.pojo.medicine.MedicationList;
import com.SmartCare.pojo.role.ElderlyInformation;
import com.SmartCare.pojo.role.EmployeeElder;
import com.SmartCare.pojo.role.User;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.SmartCare.common.enums.Constants;
import com.SmartCare.common.Result;
import com.SmartCare.common.dto.role.ElderManagerDTO;
import com.SmartCare.common.dto.role.ElderlyDTO;
import com.SmartCare.common.enums.ElderlyCareRole;
import com.SmartCare.common.exception.ServiceException;
import com.SmartCare.common.vo.role.ElderVo;
import com.SmartCare.common.vo.role.ElderVo2;
import com.SmartCare.mapper.homeInfo.CareHomeDetailsMapper;
import com.SmartCare.mapper.role.ElderlyInformationMapper;
import com.SmartCare.mapper.medicine.MedicationListMapper;
import com.SmartCare.service.role.ElderlyInformationService;
import com.SmartCare.service.role.EmployeeElderService;
import com.SmartCare.service.role.UserService;
import com.SmartCare.utils.ElderTransToDTO;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.object.UpdatableSqlQuery;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 老人信息表 服务实现类
 */
@Service
public class ElderlyInformationServiceImpl extends ServiceImpl<ElderlyInformationMapper, ElderlyInformation> implements ElderlyInformationService {
    @Autowired
    private UserService userService;
    @Autowired
    private EmployeeElderService employeeElderService;
    @Resource
    private ElderTransToDTO elderTransToDTO;
    /* @Autowired
    private UserRelationshipService userRelationshipService; */
    @Resource
    private CareHomeDetailsMapper careHomeDetailsMapper;
    @Resource
    private MedicationListMapper medicationListMapper;
    @Autowired
    private ElderlyInformationMapper elderInfoMapper;

    private final SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd");


    @Override
    public Result getElderList(Long workerId, String content) {

        //检测护工是否存在
        User user = userService.getById(workerId);
        if (user == null) {
            throw new ServiceException(Constants.CODE_400, "护工不存在");
        } else if (user.getRole() != ElderlyCareRole.CAREGIVER.getValue()) {
            throw new ServiceException(Constants.CODE_400, "该用户不是护工");
        } else if (!user.getStatus()) {
            throw new ServiceException(Constants.CODE_400, "用户已禁用");
        }

        //根据护工id先获取中间表数据
        LambdaQueryWrapper<EmployeeElder> qw = new LambdaQueryWrapper<>();
        qw.eq(EmployeeElder::getEmployeeId, workerId);
        List<EmployeeElder> list = employeeElderService.list(qw);

        //根据中间表数据获取老人id数组
        List<Long> ids = new ArrayList<>();
        for (EmployeeElder e : list) {
            ids.add(e.getElderlyId());
        }

        //根据老人ids获取老人信息列表
        if (ids.size() == 0) {
            throw new ServiceException(Constants.CODE_400, "没有该护工负责的老人信息");
        }

        LambdaQueryWrapper<ElderlyInformation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(ElderlyInformation::getElderlyId, ids);
        if (content != null && !content.isEmpty()) {
            queryWrapper.like(ElderlyInformation::getElderlyName, content);
        }

        List<ElderlyInformation> elders = super.list(queryWrapper);

        //逐个将老人信息复制到vo上返回
        List<ElderVo> result = new ArrayList<>();
        for (ElderlyInformation elder : elders) {
            ElderVo ev = new ElderVo();
            BeanUtil.copyProperties(elder, ev, true);
            //修改需要判断的两个字段
            ev.setSex(ev.getSex().equals("1") ? "男" : "女");
            ev.setSelfCareAbility(elder.getSelfCareAbility() == 1 ? "可以自理" : "不能自理");
            result.add(ev);
        }
        return Result.success(result);
    }

    @Override
    public Result updateElder(ElderlyInformation elder) {
        //先检查id是否为空
        if (elder.getElderlyId() == null) {
            throw new ServiceException(Constants.CODE_400, "未传入老人信息的id");
        }
        //检查要进行更新的老人信息是否存在
        ElderlyInformation one = getOne(new QueryWrapper<ElderlyInformation>().eq("elderly_id", elder.getElderlyId()));
        if (one == null) {
            throw new ServiceException(Constants.CODE_400, "不存在有此id的老人信息");
        }
        //进行更新
        updateById(elder);
        return Result.success();
    }

    @Override
    public Result getElderData(Long elderId) {
        //检查要进行更新的老人信息是否存在
        ElderlyInformation one = getOne(new QueryWrapper<ElderlyInformation>().eq("elderly_id", elderId));
        if (one == null) {
            throw new ServiceException(Constants.CODE_400, "不存在有此id的老人信息");
        }
        //转换成dto
        ElderlyDTO dto = elderTransToDTO.trans(one);
        return Result.success(dto);
    }

    /**
     * 根据老人id查询名称
     */
    @Override
    public String getNameById(Long id) {
        ElderlyInformation one = super.getById(id);
        if (one!=null)
            return one.getElderlyName();
        return "";
    }

    @Override
    @Transactional
    public Result gerElderInfo(Long userId) {
        //查询老人表
        LambdaQueryWrapper<ElderlyInformation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ElderlyInformation::getElderlyId, userId);
        ElderlyInformation one = getOne(queryWrapper);
        if (one == null) {
            return Result.error("用户不存在");
        }
        /* LambdaQueryWrapper<EmployeeElder> queryWrapper1 = new LambdaQueryWrapper<>();

        //老人职工关系表查询
        queryWrapper1.eq(EmployeeElder::getElderlyId, userId);
        List<EmployeeElder> list1 = employeeElderService.list(queryWrapper1);
        List<Long> nurseIds = new ArrayList<>();
        list1.forEach((item) -> nurseIds.add(item.getEmployeeId()));
        //职工信息查询
        LambdaQueryWrapper<User> queryWrapper2 = new LambdaQueryWrapper<>();
        queryWrapper2.in(User::getUserId, nurseIds);
        List<User> nurses = userService.list(queryWrapper2);
        List<NurseVo2> nurseVo2s = new ArrayList<>();
        nurses.forEach((item) -> {
            NurseVo2 vo2 = new NurseVo2();
            vo2.setId(item.getUserId());
            vo2.setName(item.getName());
            nurseVo2s.add(vo2);
        });

        //老人家属关系表查询
        LambdaQueryWrapper<UserRelationship> queryWrapper3 = new LambdaQueryWrapper<>();
        queryWrapper3.eq(UserRelationship::getElderlyId, userId);
        List<UserRelationship> userRels = userRelationshipService.list(queryWrapper3);
        List<Long> familyIds = new ArrayList<>();
        userRels.forEach((item) -> familyIds.add(item.getFamilyMemberId()));


        //家属信息查询
        LambdaQueryWrapper<User> queryWrapper4 = new LambdaQueryWrapper<>();
        queryWrapper4.in(User::getUserId, familyIds);
        List<User> familys = userService.list(queryWrapper2);
        List<FamilyVo2> familyVos = new ArrayList<>();
        familys.forEach((item) -> {
            FamilyVo2 vo = new FamilyVo2();
            vo.setId(item.getUserId());
            vo.setName(item.getName());
            vo.setPhone(item.getPhone());
            familyVos.add(vo);
        }); */


        //数据封装
        ElderVo2 vo = new ElderVo2();
        vo.setElderlyId(one.getElderlyId());
        vo.setIconUrl(one.getIconUrl());
        vo.setNickname(one.getElderlyName());
        vo.setCareHomeName(careHomeDetailsMapper.selectById(one.getCurrentCareHomeId()).getName());

        return Result.success(vo);
    }

    @Override
    public Result queryElderData(String name) {
        //判空
        if (name == null) {
            return Result.error("养老院名称不能为空");
        }
        //获取养老院信息
        CareHomeDetails careHome = careHomeDetailsMapper.selectOne(new QueryWrapper<CareHomeDetails>().eq("name", name));
        //获取该养老院的老人信息
        List<ElderlyInformation> list = list(new QueryWrapper<ElderlyInformation>().eq("current_care_home_id", careHome.getId()));
        //获取相关数据
        ElderManagerDTO dto = new ElderManagerDTO(list);

        return Result.success(dto);
    }

    @Override
    public Result managerGetList(Integer pageNum, Integer pageSize, String keyword, String type, String name) {
        //判空
        if (name == null) {
            return Result.error("养老院名称不能为空");
        }
        //获取养老院信息
        CareHomeDetails careHome = careHomeDetailsMapper.selectOne(new QueryWrapper<CareHomeDetails>().eq("name", name));

        if (careHome == null) {
            return Result.error("养老院信息不存在");
        }
        //分页
        IPage<ElderlyInformation> iPage = new Page<>(pageNum, pageSize);
        QueryWrapper<ElderlyInformation> qw = new QueryWrapper<>();
        qw.eq("current_care_home_id", careHome.getId());
        qw.like(type, keyword);
        IPage<ElderlyInformation> page = page(iPage, qw);
        return Result.success(page);
    }

    @Override
    public Result addElder(ElderlyInformation elder) {
        if (elder != null) {
            save(elder);
        } else {
            return Result.error("老人信息不能为空");
        }
        return Result.success();
    }

    @Override
    public void export(HttpServletResponse response, String id) {
        //查询药品数据
        List<ElderlyInformation> list = list(new QueryWrapper<ElderlyInformation>().eq("current_care_home_id", id));

        //创建一个新的Excel工作簿
        try (Workbook workbook = new XSSFWorkbook()) {
            // 创建一个工作表
            Sheet sheet = workbook.createSheet("Elders");

            //创建标题行
            Row headerRow = sheet.createRow(0);
            headerRow.createCell(0).setCellValue("老人姓名");
            headerRow.createCell(1).setCellValue("年龄");
            headerRow.createCell(2).setCellValue("性别");
            headerRow.createCell(3).setCellValue("床号");
            headerRow.createCell(4).setCellValue("自理能力");
            headerRow.createCell(5).setCellValue("认知能力");
            headerRow.createCell(6).setCellValue("身份证号");
            headerRow.createCell(7).setCellValue("入院日期");
            headerRow.createCell(8).setCellValue("出院日期");

            //填充数据行
            int rowNum = 1;
            for (ElderlyInformation elder : list) {
                //转成dto
                ElderlyDTO dto = elderTransToDTO.trans(elder);

                Row dataRow = sheet.createRow(rowNum++);

                if (dto.getElderlyName() != null) {
                    dataRow.createCell(0).setCellValue(dto.getElderlyName());
                }
                if (dto.getAge() != null) {
                    dataRow.createCell(1).setCellValue(dto.getAge());
                }
                if (dto.getSex() != null) {
                    dataRow.createCell(2).setCellValue(dto.getSex());
                }
                if (dto.getBedNumber() != null) {
                    dataRow.createCell(3).setCellValue(dto.getBedNumber());
                }
                if (dto.getSelfCareAbility() != null) {
                    dataRow.createCell(4).setCellValue(dto.getSelfCareAbility());
                }
                if (dto.getAwareness() != null) {
                    dataRow.createCell(5).setCellValue(dto.getAwareness());
                }
                if (dto.getIdCardNumber() != null) {
                    dataRow.createCell(6).setCellValue(dto.getIdCardNumber());
                }
                if (dto.getAdmissionDate() != null) {
                    dataRow.createCell(7).setCellValue(s.format(dto.getAdmissionDate()));
                }
                if (dto.getDischargeDate() != null) {
                    dataRow.createCell(8).setCellValue(s.format(dto.getDischargeDate()));
                }
            }
            //设置响应头
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-Disposition", "attachment; filename=ElderExport.xlsx");

            // 将工作簿内容写入响应输出流
            workbook.write(response.getOutputStream());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Result importElder(MultipartFile file, Long id) {
        try (Workbook workbook = new XSSFWorkbook(file.getInputStream())) {
            Sheet sheet = workbook.getSheetAt(0);
            Iterator<Row> rowIterator = sheet.iterator();

            while (rowIterator.hasNext()) {
                Row row = rowIterator.next();
                if (row.getRowNum() == 0) {
                    continue;
                }
                ElderlyInformation elder = new ElderlyInformation();
                //设置名称
                elder.setElderlyName(row.getCell(0).getStringCellValue());
                //设置年龄
                if (row.getCell(1) != null) {
                    elder.setAge((int) row.getCell(1).getNumericCellValue());
                }
                //设置性别
                if (row.getCell(2).getStringCellValue().equals("男")) {
                    elder.setSex(1);
                } else if (row.getCell(2).getStringCellValue().equals("女")) {
                    elder.setSex(0);
                } else {
                    elder.setSex(null);
                }
                //设置床号
                if (row.getCell(3) != null) {
                    elder.setBedNumber((int) row.getCell(3).getNumericCellValue());
                }
                //设置自理能力
                if (row.getCell(4).getStringCellValue().equals("能力完好")) {
                    elder.setSelfCareAbility(0);
                } else if (row.getCell(4).getStringCellValue().equals("轻度受损")) {
                    elder.setSelfCareAbility(1);
                } else if (row.getCell(4).getStringCellValue().equals("中度受损")) {
                    elder.setSelfCareAbility(2);
                } else if (row.getCell(4).getStringCellValue().equals("重度受损")) {
                    elder.setSelfCareAbility(3);
                } else {
                    elder.setSelfCareAbility(null);
                }
                //设置认知能力
                elder.setAwareness(row.getCell(5).getStringCellValue());
                //设置身份证号
                elder.setIdCardNumber(row.getCell(6).getStringCellValue());
                //入院日期
                if (row.getCell(7) != null) {
                    java.util.Date date = s.parse(row.getCell(7).getStringCellValue());
                    elder.setAdmissionDate(date);
                }
                //出院日期
                if (row.getCell(8) != null) {
                    Date date = s.parse(row.getCell(8).getStringCellValue());
                    elder.setDischargeDate(date);
                }
                //养老院id
                elder.setCurrentCareHomeId(id);
                save(elder);
            }
        } catch (IOException | ParseException e) {
            throw new RuntimeException(e);
        }

        return Result.success();
    }

    @Override
    public List<Long> getIdsByHomeId(Long homeId) {
        LambdaQueryWrapper<ElderlyInformation> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ElderlyInformation::getCurrentCareHomeId, homeId);
        List<ElderlyInformation> list = list(wrapper);

        List<Long> ids = new ArrayList<>();

        list.forEach((item) -> ids.add(item.getElderlyId()));
        return ids;
    }

    //更新老人信息
    @Override
    public Result updateInfo(Long elderId, String name, Integer sex, Integer age, String imageUrl,String iconUrl) {
        if (name == null && sex == null && age == null && imageUrl == null) {
            return Result.error("无参数传递");
        }
        LambdaUpdateWrapper<ElderlyInformation> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(ElderlyInformation::getElderlyId, elderId);
        //1.判断其他字段进行非空或null判断 如果有值使用wrapper.set进行设置
        if (name != null && !name.isEmpty()) {
            wrapper.set(ElderlyInformation::getElderlyName, name);
        }
        if (sex != null) {
            wrapper.set(ElderlyInformation::getSex, sex);
        }
        if (age != null) {
            wrapper.set(ElderlyInformation::getAge, age);
        }
        if (imageUrl != null && !imageUrl.isEmpty()) {
            wrapper.set(ElderlyInformation::getImage, imageUrl);
        }
        if (iconUrl!=null && !iconUrl.isEmpty()){
            wrapper.set(ElderlyInformation::getIconUrl,iconUrl);
        }
        //2.调用更新方法
        boolean res = update(wrapper);
        if (res) {
            return Result.success();
        } else {
            return Result.error("更新老年人信息失败");
        }
    }

    @Override
    public Result getElders(String careHomeName, Boolean b) {
        //获取养老院并判空
        CareHomeDetails careHome = careHomeDetailsMapper.selectOne(new QueryWrapper<CareHomeDetails>().eq("name", careHomeName));
        if (careHome == null) {
            return Result.error(Constants.CODE_400, "养老院不存在");
        }
        //获取所有药单项
        List<MedicationList> list = medicationListMapper.selectList(new QueryWrapper<>());
        //获取药单项所归属的老人id集合，即拥有药单的老人id集合，注意这些id也包括其他养老院的老人id
        List<Long> listElderIds = list.stream().map(MedicationList::getElderlyId).collect(Collectors.toList());
        //获取该养老院所有的老人
        List<ElderlyInformation> elders = list(new QueryWrapper<ElderlyInformation>().eq("current_care_home_id", careHome.getId()));
        //使用filter去除id在上面获取的id集合中的老人
        List<ElderlyInformation> result;
        //获取的是有药单的还是无药单的
        if (b) {
            result = elders.stream().filter(elder -> listElderIds.contains(elder.getElderlyId())).collect(Collectors.toList());
        } else {
            result = elders.stream().filter(elder -> !listElderIds.contains(elder.getElderlyId())).collect(Collectors.toList());
        }
        //将符合条件的老人转成dto返回
        List<ElderlyDTO> dtos = new ArrayList<>();
        for (ElderlyInformation elder : result) {
            dtos.add(elderTransToDTO.trans(elder));
        }
        return Result.success(dtos);
    }

    @Override
    public Result getElderListByName(String name) {
        //获取养老院并判空
        CareHomeDetails careHome = careHomeDetailsMapper.selectOne(new QueryWrapper<CareHomeDetails>().eq("name", name));
        if (careHome == null) {
            return Result.error(Constants.CODE_400, "养老院不存在");
        }
        return Result.success(list(new QueryWrapper<ElderlyInformation>().eq("current_care_home_id", careHome.getId())));
    }

    //游客->老人 身份修改
    @Override
    public Result toElderRole(String name, String careHomeName,String openid,String iconUrl) {
        CareHomeDetails one1 = careHomeDetailsMapper.selectOne(new LambdaQueryWrapper<CareHomeDetails>().eq(CareHomeDetails::getName, careHomeName));
        Long careHomeId = one1.getId();
        //查询老人信息
        LambdaQueryWrapper<ElderlyInformation> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ElderlyInformation::getElderlyName,name);
        wrapper.eq(ElderlyInformation::getCurrentCareHomeId,careHomeId);
        ElderlyInformation one = getOne(wrapper);

        if (one!=null){
            // 更新用户信息
            userService.update(new LambdaUpdateWrapper<User>().eq(User::getOpenid, openid).set(User::getRole, 0).set(User::getAvatarUrl,iconUrl).set(User::getCareHomeName,careHomeName));
            //获取当前的userId
            LambdaQueryWrapper<User> userWrapper = new LambdaQueryWrapper<>();
            userWrapper.eq(User::getOpenid,openid);
            User user = userService.getOne(userWrapper);

            //同时更新老人表中elderlyId和iconUrl
            LambdaUpdateWrapper<ElderlyInformation> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(ElderlyInformation::getElderlyName,name);
            updateWrapper.eq(ElderlyInformation::getCurrentCareHomeId,careHomeId);
            updateWrapper.set(ElderlyInformation::getElderlyId,user.getUserId());
            updateWrapper.set(ElderlyInformation::getIconUrl,iconUrl);

            // 更新老人信息
            elderInfoMapper.update(new ElderlyInformation(),updateWrapper);
            return Result.success("申请成功");
        }else {
            // 更新用户信息
            userService.update(new LambdaUpdateWrapper<User>().eq(User::getOpenid, openid).set(User::getRole, 0).set(User::getAvatarUrl,iconUrl).set(User::getCareHomeName,careHomeName));
            // 获取用户信息
            User user = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getOpenid, openid));
            // 创建并保存新的老人信息
            ElderlyInformation newElderlyInformation = ElderlyInformation.builder()
                    .elderlyId(user.getUserId())
                    .elderlyName(name)
                    .currentCareHomeId(careHomeId)
                    .iconUrl(iconUrl)
                    .build();
            elderInfoMapper.insert(newElderlyInformation);
            return Result.success("申请成功");
        }
    }

    @Override
    public Result deleteElder(Long id) {
        ElderlyInformation one = getById(id);
        if (one != null) {
            removeById(id);
        } else {
            return Result.error("老人不存在");
        }
        return Result.success();
    }

}
